/**
 * @file Thread.h
 * @author zeppyrz (zeppyrz@gmail.com)
 * @brief Thread class
 * @version 0.1
 * @date 2025-11-03
 *
 * @copyright Copyright (c) 2025
 *
 */

#ifndef ZEDISK_THREAD_H
#define ZEDISK_THREAD_H

#include <event2/util.h>

#include <list>
#include <memory>
#include <mutex>
#include <thread>

// forward declaration
struct event;
struct event_base;

namespace ZeDisk {

class Task;

/**
 * @brief Thread class
 */
class Thread {
 public:
  /**
   * @brief Construct a new Thread object
   *
   * @param id thread id
   */
  explicit Thread(int id);
  ~Thread();
  /**
   * @brief Start the thread
   */
  bool Start();
  void Stop();
  /**
   * @brief 线程运行函数
   */
  void Main();
  /**
   * @brief 安装线程，初始化event_base和管道监听事件用于激活
   */
  bool SetUp();
  /**
   * @brief Join the thread
   */
  void Join();
  /**
   * @brief 接受线程发出的激活消息
   */
  void Notify(evutil_socket_t, short);
  /**
   * @brief 激活线程
   */
  void Activate();
  /**
   * @brief 添加Task
   */
  void AddTask(std::shared_ptr<Task>);

  void ClearTaskCallback(evutil_socket_t, short);
 private:
  /**
   * @brief 线程 id
   */
  int id_;
  /**
   * @brief 线程
   */
  std::thread thread_;
  bool running_;
  bool joined_;
  /**
   * @brief 用来唤醒线程的eventfd
   */
  evutil_socket_t notify_send_fd;
  /**
   * libevent的事件循环
   */
  event_base *base_;

  /**
   * @brief 任务列表互斥锁
   */
  std::mutex tasks_mtx_;
  /**
   * @brief 任务列表
   */
  std::list<std::shared_ptr<Task>> tasks_;
  std::list<std::shared_ptr<Task>> activated_tasks_;
  event *clear_task_timer_;
};

}  // namespace ZeDisk

#endif  // ZEDISK_THREAD_H